package org.odefu.components.roguelike.renderer
{
	import com.pblabs.engine.debug.Logger;
	import com.pblabs.engine.entity.IEntity;
	import com.pblabs.engine.entity.PropertyReference;
	import com.pblabs.engine.serialization.TestForMetadata;
	import com.pblabs.rendering2D.BitmapRenderer;
	
	import flash.display.BitmapData;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	
	import spark.effects.easing.Sine;
	
	public class CharRendererComponent extends BitmapRenderer
	{
		private var textField:TextField;
		
		private var canvas:BitmapData;
		
		private var canvasRect:Rectangle;
		
		public function CharRendererComponent()
		{
			super();
			
			textField = new TextField();
		}
		
		public override function register(owner:IEntity, name:String):void
		{
			super.register(owner, name);
			
			const size:Point = owner.getProperty(sizeProperty);
			
			textField.width = size.x;
			textField.height = size.y;
			
			const format:TextFormat = new TextFormat();
			format.size = size.y;
			textField.defaultTextFormat = format;
			
			canvas = new BitmapData(size.x + 1, size.y + 1);
			canvasRect = new Rectangle(size.x + 1, size.y + 1);
			bitmapData = canvas;
			render();
		}
		
		public override function unregister():void
		{
			super.unregister();
			
			textField = null;
			canvas = null;
			canvasRect = null;
		}
		
		public function set border(value:Boolean):void
		{
			if (textField.border != value)
			{
				textField.border = value;
				render();
			}
		}
		
		public function set borderColor(color:uint):void
		{
			if (textField.borderColor != color)
			{
				textField.borderColor = color;
				render();
			}
		}
		
		/**
		 * Set the character to be rendered. The given string must contain only one character.
		 */
		public function set char(char:String):void
		{
			if (char && char.length == 1)
			{
				textField.text = char;
				render();
			}
		}
		
		/**
		 * Gets the current character.
		 */
		public function get char():String
		{
			return textField.text;
		}
		
		/**
		 * Set the filters for the textfield used to render the character. Set to null to clear them.
		 */ 
		public function set filters(filters:Array):void
		{
			textField.filters = filters;
			render();
		}
		
		private function render():void
		{
			if (canvas)
			{
				canvas.lock();
				canvas.fillRect(canvasRect, 0x00000000);
				canvas.draw(textField);
				canvas.unlock();
			}
		}
	}
}